﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmHoaDonChiTiet : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private bool allowCloseForm = true;
        public static int hientrang = 0;
        private HoaDonBanChiTietBOCollection HoaDonBanChiTietBOCollection = HoaDonBanChiTietBOCollection.NewHoaDonBanChiTietBOCollection();
        private HoaDonBanBO HoaDonBanBO = HoaDonBanBO.NewRootHoaDonBanBO();

        private HoaDonBanChiTietBOCollection HoaDonBanChiTietBOCollection1 = HoaDonBanChiTietBOCollection.NewHoaDonBanChiTietBOCollection();
        private HoaDonBanBO HoaDonBanBO1 = HoaDonBanBO.NewRootHoaDonBanBO();

        #endregion variant

        //=====================================
        #region form
        public FrmHoaDonChiTiet(HoaDonBanBO hoaDonBanBO, HoaDonBanChiTietBOCollection hoaDonBanChiTietBOCollection)
        {
            InitializeComponent();
            this.KeyPreview = true;


            this.HoaDonBanBO = this.HoaDonBanBO1 = hoaDonBanBO;
            this.HoaDonBanChiTietBOCollection = this.HoaDonBanChiTietBOCollection1 = hoaDonBanChiTietBOCollection;

            this.Load += new EventHandler(FrmHoaDonChiTiet_Load);
            this.Shown += new EventHandler(FrmHoaDonChiTiet_Shown);
            this.FormClosing += new FormClosingEventHandler(FrmHoaDonChiTiet_FormClosing);

            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnInvaLuu.Click += new EventHandler(btnPrinSave_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);

            this.grdViewHoaDonBanChiTiet.ShowingEditor += new CancelEventHandler(grdView_ShowingEditor);
            this.KeyDown += new KeyEventHandler(FrmHoaDonChiTiet_KeyDown);
        }

        void FrmHoaDonChiTiet_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Q && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F10))
                this.Close();
            if ((e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F6))
                Save();
            if ((e.KeyCode == Keys.P && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F2))
                btnPrinSave_Click(null, null);
        }

        private void FrmHoaDonChiTiet_Shown(object sender, EventArgs e)
        {
            this.lookUpEditKhachHang.Focus();
        }

        private void FrmHoaDonChiTiet_Load(object sender, EventArgs e)
        {
            //SetFormStatus(this.formStatus);


            Utility.InitControl(this.reLookUpMatHang);
            Utility.InitControl(this.reLookUpDonViTinh);
            Utility.InitControl(this.reLookUpDMKhoID);
            Utility.InitControl(this.lookUpEditKhachHang);
            Utility.InitControl(this.lookUpNo, "StrSoHieu", "StrSoHieu");
            Utility.InitControl(this.lookUpCo, "StrSoHieu", "StrSoHieu");

            RefreshData();

            this.spinEditPhucVu.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditGiamGia.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditChietKhau.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditVAT.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.spinEditTienPhatSinh.ValueChanged += new System.EventHandler(this.spinEditTienPhatSinh_ValueChanged);
            this.grdViewHoaDonBanChiTiet.CellValueChanged += new CellValueChangedEventHandler(this.grdViewHoaDonBanChiTiet_CellValueChanged);

            SoHieuTaiKhoanBOCollection soHieuTaiKhoanBOCollection = SoHieuTaiKhoanBOCollection.GetSoHieuTaiKhoanBOCollection();
            soHieuTaiKhoanBOCollection.Sort();
            Utility.SetData(this.lookUpNo, soHieuTaiKhoanBOCollection, soHieuTaiKhoanBOCollection.Count);
            Utility.SetData(this.lookUpCo, soHieuTaiKhoanBOCollection, soHieuTaiKhoanBOCollection.Count);

            this.lookUpNo.EditValue = "131";
            this.lookUpCo.EditValue = "531";
        }

        private void FrmHoaDonChiTiet_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }

        #endregion form

        //=====================================
        #region control


        private void spinEditTienPhatSinh_ValueChanged(object sender, EventArgs e)
        {
            TinhTien();
        }
        #endregion control

        //=====================================
        #region button

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnPrinSave_Click(object sender, EventArgs e)
        {
            Save();
            if (StaticUtil.GetRealInt(HoaDonBanBO.HoaDonBanID.Value, -1) >= 0)
            {
                RHoaDonBanBO rHoaDonBanBO = RHoaDonBanBO.NewRootRHoaDonBanBO();
                rHoaDonBanBO.CopyFromHoaDonBanBO(HoaDonBanBO);
                Report.rpHoaDonBanHang rHoaDonBanHang = new TanHungLong.Report.rpHoaDonBanHang(rHoaDonBanBO, HoaDonBanChiTietBOCollection);
                rHoaDonBanHang.ShowPreviewDialog();
            }
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion button

        //=====================================
        #region grid
        private void grdView_ShowingEditor(object sender, CancelEventArgs e)
        {
            GridView grdView = (GridView)sender;

            bool del = StaticUtil.GetBool(grdView.GetFocusedRowCellValue("DELE"));
            string fieldName = grdView.FocusedColumn.FieldName;

            if (del && fieldName != "DELE")
                e.Cancel = true;
            else
                if (fieldName == "DELE" && grdView.FocusedRowHandle == GridControl.NewItemRowHandle)
                    e.Cancel = true;
        }

        private void grdViewHoaDonBanChiTiet_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                int _idMatHang = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("MatHangID"));
                int _idDonViTinh = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("DonViTinhID"));
                double _soLuong = StaticUtil.GetDouble(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("SoLuong"));
                double _soLuongTraLai = StaticUtil.GetDouble(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("SoLuongTraLai"));
                double _giaBan = StaticUtil.GetDouble(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("DonGia"));

                int kiemtraID = this.HoaDonBanChiTietBOCollection.CheckExits(_idMatHang, _idDonViTinh);
                double thanhtien = (double)_soLuong * (double)_giaBan;
                //double thanhtientralai = (double)_soLuongTraLai * (double)_giaBan;

                HoaDonBanChiTietBOCollection[kiemtraID].SoLuong = _soLuong;
                HoaDonBanChiTietBOCollection[kiemtraID].ThanhTien = thanhtien;
                //HoaDonBanChiTietBOCollection[kiemtraID].ThanhTienTraLai = thanhtientralai;
                sapxep();
                TinhTien();
            }
            catch { }
        }
        #endregion grid

        //=====================================
        #region function

        private void RefreshData()
        {
            #region

            DanhMucBOList donViTinhBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DonViTinh);
            Utility.SetData(this.reLookUpDonViTinh, donViTinhBOList, donViTinhBOList.Count);

            DanhMucBOList dmKhoBOList = DanhMucBOList.GetDanhMucBOList(LoaiDanhMuc.DanhMucKho);
            Utility.SetData(this.reLookUpDMKhoID, dmKhoBOList, dmKhoBOList.Count);

            MatHangBOList matHangBOList = MatHangBOList.GetMatHangBOList();
            Utility.SetData(this.reLookUpMatHang, matHangBOList, matHangBOList.Count);

            KhachHangBOList khachHangBOList = KhachHangBOList.GetKhachHangBOList();
            Utility.SetData(this.lookUpEditKhachHang, khachHangBOList, khachHangBOList.Count);

            #endregion BOList

            if (StaticUtil.GetInt(this.HoaDonBanBO.HoaDonBanID, -1) >= 0)
            {
                lookUpEditKhachHang.EditValue = StaticUtil.GetInt(this.HoaDonBanBO.KhachHangID, -1);
                txtNguoiMuaHang.Text = this.HoaDonBanBO.NguoiNhanHang;
                txtMaSo.Text = this.HoaDonBanBO.MaSo;
                dtNgayLapHoaDon.DateTime = this.HoaDonBanBO.NgayLapHoaDon.Value;
                txtNoidung.Text = this.HoaDonBanBO.NoiDung;
                txtGhichu.Text = this.HoaDonBanBO.GhiChu;

                sapxep();
                TinhTien();
            }
        }

        private void AddNew()
        {
            this.HoaDonBanBO = Model.HoaDonBanBO.NewRootHoaDonBanBO();
            this.HoaDonBanChiTietBOCollection = Model.HoaDonBanChiTietBOCollection.NewHoaDonBanChiTietBOCollection();
        }

        private void Save()
        {
            if (spinEditSoLuongTraLai.Value > 0)
            {
                if (MessageBox.Show("Khách hàng có trả lại Hàng đã bán của Hóa đơn?", "Thông báo! ", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    this.HoaDonBanBO.GhiChu = txtGhichu.Text.Trim();
                    this.HoaDonBanBO.TongSoTraLai = StaticUtil.GetDouble(spinEditSoLuongTraLai.Value, 0);
                    this.HoaDonBanBO.ThanhTienTraLai = StaticUtil.GetDouble(spinEditThanhTienTraLai.Value, 0);
                    this.HoaDonBanBO.GhiChu = "Có trả lại hàng đã bán";
                    this.HoaDonBanBO.Save();

                    //---------------------
                    KhachHangBO khachHangBO = KhachHangBO.GetRootKhachHangBO(this.HoaDonBanBO.KhachHangID.Value);
                    if (khachHangBO == null)
                        khachHangBO = KhachHangBO.NewRootKhachHangBO();

                    ThuChiBO thuChiBO = ThuChiBO.NewRootThuChiBO();
                    thuChiBO.LoaiPhieu = 0; //chi
                    thuChiBO.NgayLapPhieu = this.HoaDonBanBO.NgayLapHoaDon.Value;
                    thuChiBO.NgayKyNhan = DateTime.Now;
                    thuChiBO.HoaDonBanID = this.HoaDonBanBO.HoaDonBanID;
                    thuChiBO.So = this.HoaDonBanBO.MaSo;
                    thuChiBO.Co = StaticUtil.GetString(this.lookUpCo.EditValue, null);
                    thuChiBO.No = StaticUtil.GetString(this.lookUpNo.EditValue, null);
                    thuChiBO.KhachHangID = this.HoaDonBanBO.KhachHangID;
                    thuChiBO.LaKhachHang = true;
                    thuChiBO.HoTen = khachHangBO.Ten;
                    thuChiBO.SoTien = this.HoaDonBanBO.ThanhTienTraLai;
                    thuChiBO.DaNhanDuSoTien = StaticUtil.ConvertMoney2Str(thuChiBO.SoTien);
                    thuChiBO.DaKhoa = false;
                    thuChiBO.NguoiNopTien = thuChiBO.HoTen;
                    thuChiBO.DiaChi = khachHangBO.Diachi;
                    thuChiBO.LyDo = "Trả hàng Hóa đơn số: " + this.HoaDonBanBO.MaSo; 
                    thuChiBO = thuChiBO.Save();

                    //---------------------

                    this.HoaDonBanChiTietBOCollection = this.HoaDonBanChiTietBOCollection.Save();

                    int recordCount = this.HoaDonBanChiTietBOCollection.Count;
                    if (recordCount > 0)
                    {
                        for (int i = 0; i < recordCount; i++)
                        {
                            if (this.HoaDonBanChiTietBOCollection[i].SoLuongTraLai > 0)
                            {
                                TonKhoBO tonKhoBO = null;
                                int matHangID = StaticUtil.GetInt(this.HoaDonBanChiTietBOCollection[i].MatHangID, -1);
                                int donViTinhID = StaticUtil.GetInt(this.HoaDonBanChiTietBOCollection[i].DonViTinhID, -1);
                                int danhMucKhoID = StaticUtil.GetInt(this.HoaDonBanChiTietBOCollection[i].DanhMucKhoID, -1);
                                tonKhoBO = TonKhoBO.GetRootTonKhoBOByWhere("(MatHangID = " + matHangID.ToString()
                                    + ") and (DonViTinhID = " + donViTinhID.ToString()
                                    + ") and (DanhMucKhoID = " + danhMucKhoID.ToString() + ")");
                                if (StaticUtil.GetInt(tonKhoBO.TonKhoID.Value, -1) < 0) tonKhoBO = TonKhoBO.NewRootTonKhoBO();
                                tonKhoBO.MatHangID = matHangID;
                                tonKhoBO.DonViTinhID = donViTinhID;
                                tonKhoBO.DanhMucKhoID = danhMucKhoID;
                                tonKhoBO.SoLuongTon = StaticUtil.GetDouble(tonKhoBO.SoLuongTon, 0) + StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection[i].SoLuongTraLai, 0) - StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection1[i].SoLuongTraLai, 0);
                                tonKhoBO.Save();
                                MaVachBO maVachBO = null;
                                string strWhere = "MaVach = '" + this.HoaDonBanChiTietBOCollection[i].MaVach.ToString()
                                    + "' and TonKhoID = " + StaticUtil.GetInt(tonKhoBO.TonKhoID.Value, -1).ToString();
                                maVachBO = MaVachBO.GetRootMaVachBOByWhere(strWhere);
                                if (StaticUtil.GetInt(maVachBO.MaVachID.Value, -1) < 0) maVachBO = MaVachBO.NewRootMaVachBO();
                                maVachBO.TonKhoID = StaticUtil.GetInt(tonKhoBO.TonKhoID.Value, -1);
                                maVachBO.MaVach = this.HoaDonBanChiTietBOCollection[i].MaVach.ToString();
                                maVachBO.SoLuongTon = StaticUtil.GetDouble(maVachBO.SoLuongTon, 0) + StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection[i].SoLuongTraLai, 0) - StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection1[i].SoLuongTraLai, 0);
                                maVachBO.Save();

                                TraHangBO traHangBO = TraHangBO.NewRootTraHangBO();
                                traHangBO.KhachHangID = this.HoaDonBanBO.KhachHangID.Value;
                                traHangBO.MaSo = this.HoaDonBanBO.MaSo;
                                traHangBO.MatHangID = matHangID;
                                traHangBO.DonViTinhIDN = donViTinhID;
                                traHangBO.KhoID = danhMucKhoID;
                                traHangBO.SoLuong = StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection[i].SoLuongTraLai, 0) - StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection1[i].SoLuongTraLai, 0);
                                traHangBO.ThanhTienTra = StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection[i].ThanhTienTraLai, 0) - StaticUtil.GetDouble(this.HoaDonBanChiTietBOCollection1[i].ThanhTienTraLai, 0);
                                traHangBO.DienGiai = "Khách trả lại Hàng: " + this.HoaDonBanChiTietBOCollection[i].TenHang + " - ĐVT: " + this.HoaDonBanChiTietBOCollection[i].TenDonViTinh;
                                traHangBO.Save();

                            }
                        }
                    }
                    this.Close();
                }
            }

        }

        private void sapxep()
        {

            int length = HoaDonBanChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                HoaDonBanChiTietBOCollection[i].STT0 = (i + 1);
            }

            bdSourceHoaDonBanChiTiet.DataSource = HoaDonBanChiTietBOCollection;
        }

        private void TinhTien()
        {
            double tongso = 0;
            double thanhtien = 0;
            double tongsotralai = 0;
            double thanhtientralai = 0;
            double tongtien = 0;

            int length = HoaDonBanChiTietBOCollection.Count;

            for (int i = 0; i < length; i++)
            {
                tongso = tongso + HoaDonBanChiTietBOCollection[i].SoLuong.Value;
                thanhtien = thanhtien + HoaDonBanChiTietBOCollection[i].ThanhTien.Value;
                tongsotralai = tongsotralai + StaticUtil.GetDouble(HoaDonBanChiTietBOCollection[i].SoLuongTraLai, 0);
                thanhtientralai = thanhtientralai + StaticUtil.GetDouble(HoaDonBanChiTietBOCollection[i].ThanhTienTraLai, 0);
            }

            spinEditTongSo.Value = (decimal)tongso;
            spinEditThanhTien.Value = (decimal)thanhtien;

            spinEditSoLuongTraLai.Value = (decimal)tongsotralai;
            spinEditThanhTienTraLai.Value = (decimal)thanhtientralai;
            double tienKhachTra = StaticUtil.GetDouble(HoaDonBanBO.TienKhachTra, 0);
            spinEditTienKhachTra.Value = (decimal)tienKhachTra;

            double mucVAT = StaticUtil.GetDouble(spinEditVAT.Value, 0);
            double tienVAT = thanhtien * mucVAT;
            spinEditTienVAT.Value = (decimal)tienVAT;
            double mucCK = StaticUtil.GetDouble(spinEditChietKhau.Value, 0);
            double tienCK = thanhtien * mucCK;
            spinEditTienChietKhau.Value = (decimal)tienCK;
            double mucGG = StaticUtil.GetDouble(spinEditGiamGia.Value, 0);
            double tienGG = thanhtien * mucGG;
            spinEditTienGiamGia.Value = (decimal)tienGG;
            double mucPV = StaticUtil.GetDouble(spinEditPhucVu.Value, 0);
            double tienPV = thanhtien * mucPV;
            spinEditTienPhucVu.Value = (decimal)tienPV;
            double TienPhatSinh = StaticUtil.GetDouble(spinEditTienPhatSinh.Value, 0);

            tongtien = thanhtien + tienVAT + TienPhatSinh - tienCK - tienGG + tienPV;
            spinEditTongTien.Value = (decimal)tongtien;
            txtBangChu.Text = VNCurrency.ToString(tongtien);
        }

        private void DeleteMatHang(int mathangID, int donvitinhID)
        {

            if (MessageBox.Show("Bạn có muốn xóa Mặt Hàng và Đơn vị tính này không? ", "Cảnh báo!!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                HoaDonBanChiTietBOCollection.Remove(mathangID, donvitinhID);
                int _idHoaDonBanChiTiet = StaticUtil.GetInt(this.grdViewHoaDonBanChiTiet.GetFocusedRowCellValue("HoaDonBanChiTietID"), -1);

                if (_idHoaDonBanChiTiet >= 0)
                {
                    HoaDonBanChiTietBO.DeleteHoaDonBanChiTietBO(_idHoaDonBanChiTiet);
                }
                sapxep();
                TinhTien();
            }
        }

        private int kiemtraLuu()
        {
            int tempkiemtra = 1;
            string strError = "";

            //if (spinEditSoLuongTraLai.Value <= 0)
            //{
            //    tempkiemtra = 0;
            //    strError = "Chưa chọn Khách hàng";
            //}

            if (txtMaSo.Text.Trim() == "")
            {
                tempkiemtra = 0;
                strError = strError + " ;Chưa nhập Mã số";
            }

            if (tempkiemtra == 0)
                MessageBox.Show(strError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return tempkiemtra;
        }

        #endregion function

    }
}